{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "#skip\n",
    "! [ -e /content ] && pip install -Uqq fastai  # upgrade fastai on colab"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from nbdev.export2html import *\n",
    "from fastai.core.imports import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nbformat, jupyter_contrib_nbextensions\n",
    "from nbconvert.preprocessors import Preprocessor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import FileLink"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class NBConvertor:\n",
    "    \n",
    "    def _exporter():\n",
    "        exporter = MarkdownExporter(Config())\n",
    "        exporter.exclude_input_prompt=True\n",
    "        exporter.exclude_output_prompt=True\n",
    "        exporter.template_file = 'jekyll.tpl'\n",
    "        exporter.template_path.append(str((Path()/'local'/'notebook').absolute()))\n",
    "        return exporter\n",
    "\n",
    "    _re_title = re.compile(r'^\\s*#\\s+([^\\n]*)\\n')\n",
    "    cell_type,outputs,source,code,text = 'cell_type','outputs','source','code','text'\n",
    "\n",
    "    def process_output(c,s,o):\n",
    "        if c[cell_type]!=code or o is None: return s,o\n",
    "        def _f(x):\n",
    "            if text not in x: return x\n",
    "            x[text] = re.sub(r'^(.*\\S)',r'> \\1',x[text], flags=re.MULTILINE)\n",
    "            return x\n",
    "        return s,[_f(o_) for o_ in o]\n",
    "\n",
    "    def process_title(c,s,o):\n",
    "        if s.startswith('#hide'): return\n",
    "        if c[cell_type] == code: return s,o\n",
    "        if _re_title.search(s):\n",
    "            s = '---\\n' + _re_title.sub(r'title: \"\\1\"', s) + '\\n---'\n",
    "            s = re.sub('^- ', '', s, flags=re.MULTILINE)\n",
    "        return s,o\n",
    "\n",
    "    def apply_all(x, fs, **kwargs):\n",
    "        for f in fs:\n",
    "            s,o = f(x, x[source], x.get(outputs,None), **kwargs) or (None,None)\n",
    "            x[source]=s\n",
    "            if s is None: x=None; break\n",
    "            elif o is not None: x[outputs] = o\n",
    "        return x\n",
    "\n",
    "    def convert(fname, dest=None, cell_procs=None):\n",
    "        fname = Path(fname)\n",
    "        (fname.parent/'md_out').mkdir(exist_ok=True)\n",
    "        if dest is None: dest = (fname.parent/'md_out'/fname.name).with_suffix('.md')\n",
    "        if cell_procs is None: cell_procs = [process_title,process_output]\n",
    "        with open(fname,'r') as f: nb = nbformat.reads(f.read(), as_version=4)\n",
    "        nb['cells'] = [o for o in [apply_all(c, cell_procs) for c in nb['cells']] if o is not None]\n",
    "        exp = _exporter()\n",
    "        with open(dest,'w') as f: f.write(exp.from_notebook_node(nb)[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "name = 'delegation'\n",
    "convert(Path.cwd()/f'{name}.ipynb')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<a href='md_out/delegation.md' target='_blank'>md_out/delegation.md</a><br>"
      ],
      "text/plain": [
       "/home/jhoward/git/fastai_dev/dev/md_out/delegation.md"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "FileLink(f'md_out/{name}.html')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
